package util;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import chui.ZoneMonitor;



/**
 * @author rpitts@gmu.edu
 *
 */
public class ListeningServer extends Thread {

	private static Boolean keepGoing = true; 
	private int port = 0;
	ZoneMonitor zM = null;

	public ListeningServer (ZoneMonitor zM, int port) {
		super();
		this.port = port;
		this.zM = zM;
		this.start();
	}


	public void close () {
		// sanity check--stop if it receives another message and is still running
		keepGoing = false;		

	}

	@Override
	public void run() {

		System.out.println ("Starting Listening Server");

		// Create a server socket to accept client connection requests
		ServerSocket servSock = null;
		try {
			servSock = new ServerSocket(this.port);
		} catch (IOException e) {
			e.printStackTrace();
		}

		//element = message.split(DataHandler.getUnitSeparator());
		while(keepGoing) {  // run forever, accepting and servicing connections

			Socket sock = null;
			try {
				sock = servSock.accept();
			} catch (IOException e) {
				e.printStackTrace();
			} // Get client connection
			
			// open a process to process incoming message
			System.out.println("Request received. Spawning new thread to process it.");
			new SingleSocketProcess(zM, sock);

		} // while(keepGoing)

		// Close the server socket
		try {
			servSock.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	} // handleSocketServer() 

}

